<template>
  <div class="page-container">
    <h1>日志管理</h1>
    
    <!-- 搜索条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="操作用户">
          <el-input v-model="searchForm.username" placeholder="请输入操作用户" clearable />
        </el-form-item>
        <el-form-item label="用户类型" style="width: 250px;">
          <el-select v-model="searchForm.userType" placeholder="请选择用户类型" clearable>
            <el-option label="企业账号" :value="1" />
            <el-option label="市账号" :value="2" />
            <el-option label="省账号" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作模块">
          <el-input v-model="searchForm.operationModule" placeholder="请输入操作模块" clearable />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="响应状态" style="width: 250px;">
          <el-select v-model="searchForm.responseStatus" placeholder="请选择响应状态" clearable>
            <el-option label="成功" :value="200" />
            <el-option label="失败" :value="500" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchLogs">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="exportLogs">导出日志</el-button>
          <el-button type="danger" @click="showClearDialog">清理日志</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 日志列表 -->
    <el-card class="log-table-card" shadow="hover">
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="logsList"
          style="width: 100%"
          row-key="logId"
        >
        <el-table-column prop="logId" label="日志ID" width="80" />
        <el-table-column prop="username" label="操作用户" width="120" />
        <el-table-column prop="userType" label="用户类型" width="100">
          <template #default="scope">
            <!-- 与后端 AccountTypeEnum 对应：0-省级账号 1-企业账号 2-市级账号 -->
            <el-tag v-if="scope.row.userType === 0" type="danger">省账号</el-tag>
            <el-tag v-else-if="scope.row.userType === 1" type="success">企业账号</el-tag>
            <el-tag v-else-if="scope.row.userType === 2" type="warning">市账号</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="operationModule" label="操作模块" width="120" />
        <el-table-column prop="operationDesc" label="操作描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="requestMethod" label="请求方法" width="100" />
        <el-table-column prop="responseStatus" label="响应状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.responseStatus === 200" type="success">成功</el-tag>
            <el-tag v-else type="danger">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="executionTime" label="执行时间(ms)" width="120" />
        <el-table-column prop="operationTime" label="操作时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewLogDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      </div>
    </el-card>
    
    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="60%"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="日志ID">{{ currentLog.logId }}</el-descriptions-item>
        <el-descriptions-item label="操作用户">{{ currentLog.username }}</el-descriptions-item>
        <el-descriptions-item label="用户类型">
          <!-- 与后端 AccountTypeEnum 对应：0-省级账号 1-企业账号 2-市级账号 -->
          <el-tag v-if="currentLog.userType === 1" type="success">企业账号</el-tag>
          <el-tag v-else-if="currentLog.userType === 2" type="warning">市账号</el-tag>
          <el-tag v-else-if="currentLog.userType === 0" type="danger">省账号</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="企业ID">{{ currentLog.enterpriseId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="操作模块">{{ currentLog.operationModule }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ currentLog.operationTime }}</el-descriptions-item>
        <el-descriptions-item label="请求URL" :span="2">{{ currentLog.requestUrl }}</el-descriptions-item>
        <el-descriptions-item label="请求方法">{{ currentLog.requestMethod }}</el-descriptions-item>
        <el-descriptions-item label="响应状态">
          <el-tag v-if="currentLog.responseStatus === 200" type="success">成功</el-tag>
          <el-tag v-else type="danger">失败</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="执行时间">{{ currentLog.executionTime }}ms</el-descriptions-item>
        <el-descriptions-item label="操作描述" :span="2">{{ currentLog.operationDesc }}</el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2">
          <pre>{{ formatJson(currentLog.requestParams) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentLog.errorMessage" label="错误信息" :span="2">
          <pre class="error-message">{{ currentLog.errorMessage }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    
    <!-- 清理日志对话框 -->
    <el-dialog
      v-model="clearDialogVisible"
      title="清理日志"
      width="30%"
    >
      <el-alert
        title="警告：清理操作不可恢复，请谨慎操作！"
        type="warning"
        :closable="false"
        style="margin-bottom: 20px"
      />
      <el-form :model="clearForm" label-width="120px">
        <el-form-item label="清理截止日期">
          <el-date-picker
            v-model="clearForm.endTime"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="确认清理">
          <el-checkbox v-model="clearForm.confirm">我已了解清理操作不可恢复</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearDialogVisible = false">取消</el-button>
          <el-button
            type="danger"
            :disabled="!clearForm.confirm || !clearForm.endTime"
            @click="clearLogs"
          >
            确认清理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logsApi from '../../api/logs.js'

// 搜索表单
const searchForm = reactive({
  username: '',
  userType: '',
  enterpriseId: '',
  operationModule: '',
  startTime: '',
  endTime: '',
  responseStatus: ''
})

// 日期范围选择
const dateRange = ref([])

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 日志列表数据
const logsList = ref([])
const loading = ref(false)

// 日志详情相关
const detailDialogVisible = ref(false)
const currentLog = ref({})

// 清理日志相关
const clearDialogVisible = ref(false)
const clearForm = reactive({
  endTime: '',
  confirm: false
})

// 初始化加载
onMounted(() => {
  getLogsList()
})

// 获取日志列表
const getLogsList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    
    // 转换参数名称，确保与后端接口一致（将驼峰命名转为下划线命名）
    const convertedParams = {
      username: params.username,
      userType: params.userType,
      enterpriseId: params.enterpriseId,
      operationModule: params.operationModule,
      startTime: params.startTime,
      endTime: params.endTime,
      responseStatus: params.responseStatus,
      page: params.page,
      pageSize: params.pageSize
    }
    
    const res = await logsApi.getLogsList(convertedParams)

    // 统一处理业务错误，例如登录超时(code=901)
    if (!res || res.code !== 200 || !res.data) {
      if (res && res.code === 901) {
        ElMessage.error('登录超时，请重新登录')
        window.location.href = '/login'
      } else {
        ElMessage.error(res?.info || '获取日志列表失败')
      }
      logsList.value = []
      pagination.total = 0
      return
    }

    // 将后端返回的下划线命名转为驼峰命名
    logsList.value = (res.data.list || []).map(item => ({
      logId: item.logId,
      username: item.username,
      userType: item.userType,
      enterpriseId: item.enterpriseId,
      operationModule: item.operationModule,
      operationDesc: item.operationDesc,
      requestMethod: item.requestMethod,
      responseStatus: item.responseStatus,
      executionTime: item.executionTime,
      operationTime: item.operationTime,
      requestUrl: item.requestUrl,
      requestParams: item.requestParams,
      errorMessage: item.errorMessage
    }))
    
    pagination.total = res.data.totalCount || 0
  } catch (error) {
    console.error('获取日志列表失败', error)
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

// 查看日志详情
const viewLogDetail = async (row) => {
  try {
    const res = await logsApi.getLogDetail(row.logId)
    
    // 将后端返回的下划线命名转为驼峰命名
    currentLog.value = {
      logId: res.data.logId,
      username: res.data.username,
      userType: res.data.userType,
      enterpriseId: res.data.enterpriseId,
      operationModule: res.data.operationModule,
      operationDesc: res.data.operationDesc,
      requestMethod: res.data.requestMethod,
      responseStatus: res.data.responseStatus,
      executionTime: res.data.executionTime,
      operationTime: res.data.operationTime,
      requestUrl: res.data.requestUrl,
      requestParams: res.data.requestParams,
      errorMessage: res.data.errorMessage
    }
    
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取日志详情失败', error)
    ElMessage.error('获取日志详情失败')
  }
}

// 导出日志
const exportLogs = async () => {
  try {
    // 转换参数名称，确保与后端接口一致（将驼峰命名转为下划线命名）
    const convertedParams = {
      username: searchForm.username,
      userType: searchForm.userType,
      enterpriseId: searchForm.enterpriseId,
      operationModule: searchForm.operationModule,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime,
      responseStatus: searchForm.responseStatus
    }
    
    const res = await logsApi.exportLogs(convertedParams)
    
    // 创建下载链接
    const blob = new Blob([res.data])
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `操作日志_${new Date().toISOString().split('T')[0]}.xlsx`
    link.click()
    URL.revokeObjectURL(link.href)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出日志失败', error)
    ElMessage.error('导出日志失败')
  }
}

// 显示清理日志对话框
const showClearDialog = () => {
  clearForm.endTime = ''
  clearForm.confirm = false
  clearDialogVisible.value = true
}

// 清理日志
const clearLogs = async () => {
  if (!clearForm.confirm || !clearForm.endTime) {
    ElMessage.warning('请确认清理操作并选择截止日期')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要清理 ${clearForm.endTime} 之前的所有日志吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确认清理',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 转换参数名称，确保与后端接口一致
    await logsApi.clearLogs({ endTime: clearForm.endTime })
    ElMessage.success('日志清理成功')
    clearDialogVisible.value = false
    getLogsList() // 重新加载数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理日志失败', error)
      ElMessage.error('清理日志失败')
    }
  }
}

// 日期范围变化处理
const handleDateChange = (val) => {
  if (val) {
    searchForm.startTime = val[0]
    searchForm.endTime = val[1]
  } else {
    searchForm.startTime = ''
    searchForm.endTime = ''
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  getLogsList()
}

// 页码变化
const handleCurrentChange = (page) => {
  pagination.page = page
  getLogsList()
}

// 搜索日志
const searchLogs = () => {
  pagination.page = 1
  getLogsList()
}

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  dateRange.value = []
  pagination.page = 1
  getLogsList()
}

// 格式化JSON显示
const formatJson = (jsonStr) => {
  if (!jsonStr) return '-'
  try {
    const obj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    return jsonStr
  }
}
</script>

<style scoped lang="scss">
.page-container {
  h1 {
    margin-bottom: 20px;
    color: #1f2937;
    font-size: 24px;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .log-table-card {
    margin-bottom: 20px;
  }
  
  .table-section {
    padding: 10px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  pre {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    max-height: 200px;
    overflow: auto;
    margin: 0;
    font-family: monospace;
    white-space: pre-wrap;
    word-break: break-all;
  }
  
  .error-message {
    background-color: #fef0f0;
    color: #f56c6c;
  }
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
  --el-table-row-hover-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  font-weight: bold;
  color: #303133;
}

:deep(.el-card) {
  margin-bottom: 20px;
}
</style>
